import { useEffect, useMemo, useState } from 'react';
import { useDispatch } from 'react-redux';
import { DatePicker, Form, InputNumber, Select } from 'antd';
import dayjs from 'dayjs';
import { debounce } from 'lodash';

import AdvancedAutoComplete from './AdvancedAutoComplete';
import RangeSelector from './RangeSelector';
import TreeSelector from './TreeSelector';
import WithCoverage from './WithCoverage';

export const SELECTOR_TYPES = {
  ENUM: 1,
  TEXT: 2,
  NUMBER: 3,
  RANGE: 4, // 暂时不用支持
  DATE: 5, // 暂时不用支持
  DATERANGE: 6,
  Tree: 7,
  WithCoverage: 8,
  AD_TRANSFORM_PEOPLE: 9, // 广告投放转化人群
};
const v = Object.values(SELECTOR_TYPES);

const AdvancedSelect = ({ id, value, onChange }) => {
  const [enumValues, setEnumValues] = useState([]);
  const [searchLabel, setSearchLabel] = useState('');

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch({
      type: 'label/loadTagEnum',
      payload: { tagId: id, callback: setEnumValues },
    });
  }, [id, dispatch]);
  const optinsString = JSON.stringify(enumValues);
  const options = useMemo(() => {
    return enumValues
      .filter((item) => {
        return item.value.includes(searchLabel);
      })
      .map(({ tagDataId, value }) => ({
        value: tagDataId,
        label: value,
      }));
  }, [optinsString, searchLabel]);

  const debounceFetcher = debounce(setSearchLabel, 1000);

  return (
    <Select
      options={options}
      mode="multiple"
      style={{ minWidth: '100px' }}
      dropdownMatchSelectWidth
      filterOption={false}
      onSearch={debounceFetcher}
      value={value ? value.map(({ tagDataId }) => tagDataId) : []}
      onChange={(_, detailValue) => {
        onChange(
          detailValue.map((v) => {
            const { value, label } = v;
            return { tagDataId: value, value: label };
          }),
        );
      }}
    />
  );
};

const AdvancedDateRange = ({ value, onChange, checkData }) => {
  const dateValue = (value ?? []).map((value) => dayjs(value));
  const { maxMax, minMin } = checkData;
  return (
    <DatePicker.RangePicker
      value={dateValue}
      onChange={(dates) => {
        const [start, end] = dates;
        onChange([start.format('YYYYMMDD'), end.format('YYYYMMDD')]);
      }}
      // todo: 后端有问题，暂时注释小
      disabledDate={(date) => {
        const max = dayjs(maxMax);
        const min = dayjs(minMin);
        return date.isBefore(min) || date.isAfter(max);
      }}
    />
  );
};

const TagSelectorFilter = ({ tagInfo, coverage, rate, p_date }) => {
  const { id, required, tagName, tagType, checkData } = tagInfo;
  if (!v.includes(tagType)) {
    return null;
  }
  // 穿梭框
  if (tagType === SELECTOR_TYPES.WithCoverage) {
    return (
      <Form.Item label={tagName} rules={[{ required: required }]} name={id}>
        <WithCoverage id={id} />
      </Form.Item>
    );
  }
  // 树形结构
  if (tagType === SELECTOR_TYPES.Tree) {
    return (
      <Form.Item label={tagName} rules={[{ required: required }]} name={id}>
        <TreeSelector id={id} coverage={coverage} rate={rate} />
      </Form.Item>
    );
  }
  // 枚举
  if (tagType === SELECTOR_TYPES.ENUM) {
    return (
      <Form.Item label={tagName} rules={[{ required: required }]} name={id}>
        <AdvancedSelect id={id} />
      </Form.Item>
    );
  }
  // 可文本  可搜索选择
  if (tagType === SELECTOR_TYPES.TEXT) {
    return (
      <Form.Item label={tagName} rules={[{ required: required }]} name={id}>
        <AdvancedAutoComplete
          id={id}
          coverage={coverage}
          rate={rate}
          p_date={p_date}
        />
      </Form.Item>
    );
  }
  // number
  if (tagType === SELECTOR_TYPES.NUMBER) {
    return (
      <Form.Item label={tagName} rules={[{ required }]} name={id}>
        <InputNumber />
      </Form.Item>
    );
  }

  if (tagType === SELECTOR_TYPES.RANGE) {
    const { minMin, minMax } = checkData;
    return (
      <Form.Item
        label={tagName}
        rules={[{ required }]}
        name={id}
        initialValue={[minMin, minMax]}
      >
        <RangeSelector checkData={checkData} />
      </Form.Item>
    );
  }

  if (tagType === SELECTOR_TYPES.DATERANGE) {
    const { range } = checkData ?? {};
    return (
      <Form.Item
        label={tagName}
        rules={[
          { required: required },
          () => ({
            validator(_, [start, end]) {
              if (!range) return Promise.resolve();
              const diff = dayjs(end).diff(dayjs(start), 'days');
              if (diff <= range) {
                return Promise.resolve();
              } else {
                return Promise.reject(`时间范围不能超过 ${range} 天`);
              }
            },
          }),
        ]}
        name={id}
      >
        <AdvancedDateRange checkData={checkData} />
      </Form.Item>
    );
  }

  return null;
};

export default TagSelectorFilter;
